<template>
  <div class="fault-management-container">
              <!-- 顶部操作栏和过滤条件 -->
     <div class="header-section">
       <div class="filter-section">
         <div class="filter-content">
           <div class="filter-row">
                           <div class="filter-item">
                <el-select v-model="filters.project" placeholder="选择项目" clearable class="filter-select" @change="onFiltersChange">
                  <el-option label="全部" :value="0" />
                  <el-option
                    v-for="project in projectOptions"
                    :key="project.value"
                    :label="project.label"
                    :value="project.value"
                  />
                </el-select>
              </div>
                           <div class="filter-item">
                <el-date-picker
                  v-model="filters.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="故障开始日期"
                  end-placeholder="故障开始日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  class="filter-date"
                  @change="onFiltersChange"
                />
              </div>
             <div class="filter-item">
               <el-select v-model="filters.status" placeholder="故障状态" clearable class="filter-select" @change="onFiltersChange">
                 <el-option label="待处理" value="pending" />
                 <el-option label="处理中" value="processing" />
                 <el-option label="已解决" value="resolved" />
               </el-select>
             </div>
             <div class="filter-item">
               <el-select v-model="filters.severity" placeholder="故障等级" clearable class="filter-select" @change="onFiltersChange">
                 <el-option label="低" value="low" />
                 <el-option label="中" value="medium" />
                 <el-option label="高" value="high" />
               </el-select>
             </div>
             <div class="filter-item">
               <el-input
                 v-model="filters.keyword"
                 placeholder="搜索故障描述或责任人"
                 clearable
                 class="filter-input"
                 :prefix-icon="Search"
                 @keyup.enter="onFiltersChange"
               />
             </div>
             <div class="filter-item">
               <el-button @click="resetFilters">重置</el-button>
             </div>
           </div>
         </div>
       </div>
       
       <div class="action-buttons">
         <el-button type="primary" :icon="Plus" @click="showAddDialog">
           新增故障记录
         </el-button>
       </div>
     </div>



    <!-- 故障记录列表 -->
    <div class="fault-list-section">
      <el-card shadow="never" class="list-card">
        <div class="list-header">
          <div class="list-title">
            <span>故障记录列表</span>
            <el-tag type="info" size="small">{{ totalCount }} 条记录</el-tag>
          </div>
          <div class="list-actions">
            <el-button-group>
              <el-button :type="viewMode === 'table' ? 'primary' : ''" @click="viewMode = 'table'">
                <el-icon><List /></el-icon>
                表格视图
              </el-button>
              <el-button :type="viewMode === 'card' ? 'primary' : ''" @click="viewMode = 'card'">
                <el-icon><Grid /></el-icon>
                卡片视图
              </el-button>
            </el-button-group>
          </div>
        </div>

        <!-- 表格视图 -->
        <div v-if="viewMode === 'table'" class="table-view">
                     <el-table
             :data="paginatedFaults"
             stripe
             border
             class="fault-table"
             :header-cell-style="{ background: '#f5f7fa' }"
             height="500"
             max-height="500"
           >
            
            <el-table-column prop="projectName" label="项目名称" min-width="120" />
                                     <el-table-column prop="faultStartTime" label="故障开始时间" width="160" align="center" />
            <el-table-column prop="faultEndTime" label="故障解决时间" width="160" align="center" />
            <el-table-column label="持续时间" width="120" align="center">
              <template #default="{ row }">
                <span v-if="row.faultEndTime" class="duration-text">
                  {{ calculateDuration(row.faultStartTime, row.faultEndTime) }}
                </span>
                <span v-else class="duration-ongoing">进行中</span>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="故障描述" min-width="200" show-overflow-tooltip />
            <el-table-column prop="reason" label="故障原因" min-width="150" show-overflow-tooltip />
            <el-table-column prop="responsiblePersons" label="责任人" min-width="120" show-overflow-tooltip />
            <el-table-column prop="deductionScore" label="扣除绩效分" width="120" align="center">
              <template #default="{ row }">
                <el-tag :type="getScoreTagType(row.deductionScore)" size="small">
                  -{{ row.deductionScore }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getStatusTagType(row.status)" size="small">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="severity" label="等级" width="80" align="center">
              <template #default="{ row }">
                <el-tag :type="getSeverityTagType(row.severity)" size="small">
                  {{ getSeverityText(row.severity) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="160" align="center" />
            <el-table-column label="操作" width="250" align="center" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" size="small" :icon="View" @click="viewFault(row)">
                  查看
                </el-button>
                <el-button type="warning" size="small" :icon="Edit" @click="editFault(row)">
                  编辑
                </el-button>
                <el-button type="danger" size="small" :icon="Delete" @click="deleteFault(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 卡片视图 -->
        <div v-else class="card-view">
          <div class="fault-cards">
            <el-card
              v-for="fault in paginatedFaults"
              :key="fault.id"
              class="fault-card"
              shadow="hover"
            >
              <div class="card-header">
                <div class="fault-status">
                  <el-tag :type="getStatusTagType(fault.status)" size="small">
                    {{ getStatusText(fault.status) }}
                  </el-tag>
                </div>
              </div>
              <div class="card-content">
                <div class="fault-project">
                  <el-icon><Folder /></el-icon>
                  <span>{{ fault.projectName }}</span>
                </div>
                <div class="fault-description">{{ fault.description }}</div>
                <div class="fault-details">
                                     <div class="detail-item">
                     <span class="label">故障开始时间:</span>
                     <span class="value">{{ fault.faultStartTime }}</span>
                   </div>
                   <div class="detail-item">
                     <span class="label">故障解决时间:</span>
                     <span class="value">{{ fault.faultEndTime || '未解决' }}</span>
                   </div>
                   <div class="detail-item">
                     <span class="label">持续时间:</span>
                     <span v-if="fault.faultEndTime" class="value duration-text">
                       {{ calculateDuration(fault.faultStartTime, fault.faultEndTime) }}
                     </span>
                     <span v-else class="value duration-ongoing">进行中</span>
                   </div>
                  <div class="detail-item">
                    <span class="label">责任人:</span>
                    <span class="value">{{ fault.responsiblePersons }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="label">扣除绩效分:</span>
                    <el-tag :type="getScoreTagType(fault.deductionScore)" size="small">
                      -{{ fault.deductionScore }}
                    </el-tag>
                  </div>
                </div>
              </div>
              <div class="card-footer">
                <el-button type="primary" size="small" @click="viewFault(fault)">查看</el-button>
                <el-button type="warning" size="small" @click="editFault(fault)">编辑</el-button>
                <el-button type="danger" size="small" @click="deleteFault(fault)">删除</el-button>
              </div>
            </el-card>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="totalCount"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 新增/编辑故障记录对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑故障记录' : '新增故障记录'"
      width="900px"
      :close-on-click-modal="false"
      class="fault-dialog"
      @close="resetForm"
      top="5vh"
    >
      <div class="dialog-content">
        <!-- 表单内容 -->
        <el-form
          ref="faultFormRef"
          :model="faultForm"
          :rules="faultRules"
          label-width="120px"
          class="fault-form"
        >
          <!-- 基本信息区域 -->
          <div class="form-section">
            <div class="section-title">
              <el-icon><InfoFilled /></el-icon>
              <span>基本信息</span>
            </div>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="项目名称" prop="projectId">
                  <el-select
                    v-model="faultForm.projectId"
                    placeholder="请选择项目"
                    class="form-select"
                    filterable
                    clearable
                  >
                    <el-option label="请选择项目" :value="0" disabled />
                    <el-option
                      v-for="project in projectOptions"
                      :key="project.value"
                      :label="project.label"
                      :value="project.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="故障等级" prop="severity">
                  <el-select v-model="faultForm.severity" placeholder="请选择故障等级" class="form-select">
                    <el-option label="低" value="low">
                      <el-tag type="success" size="small">低</el-tag>
                    </el-option>
                    <el-option label="中" value="medium">
                      <el-tag type="warning" size="small">中</el-tag>
                    </el-option>
                    <el-option label="高" value="high">
                      <el-tag type="danger" size="small">高</el-tag>
                    </el-option>
                    
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 时间信息区域 -->
          <div class="form-section">
            <div class="section-title">
              <el-icon><Clock /></el-icon>
              <span>时间信息</span>
            </div>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="故障开始时间" prop="faultStartTime">
                  <el-date-picker
                    v-model="faultForm.faultStartTime"
                    type="datetime"
                    placeholder="选择故障开始时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    class="form-date"
                    :prefix-icon="Calendar"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="故障解决时间" prop="faultEndTime">
                  <el-date-picker
                    v-model="faultForm.faultEndTime"
                    type="datetime"
                    placeholder="选择故障解决时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    class="form-date"
                    :prefix-icon="Calendar"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 详细描述区域 -->
          <div class="form-section">
            <div class="section-title">
              <el-icon><Document /></el-icon>
              <span>详细描述</span>
            </div>
            <el-form-item label="故障描述" prop="description">
              <el-input
                v-model="faultForm.description"
                type="textarea"
                :rows="4"
                placeholder="请详细描述故障现象、影响范围、复现步骤等"
                maxlength="500"
                show-word-limit
                class="form-textarea"
              />
            </el-form-item>

            <el-form-item label="故障原因" prop="reason">
              <el-input
                v-model="faultForm.reason"
                type="textarea"
                :rows="4"
                placeholder="请分析故障原因、根本原因等"
                maxlength="500"
                show-word-limit
                class="form-textarea"
              />
            </el-form-item>
          </div>

          <!-- 责任人和备注区域 -->
          <div class="form-section">
            <div class="section-title">
              <el-icon><User /></el-icon>
              <span>责任人和备注</span>
            </div>
            <el-form-item label="责任人" prop="responsiblePersons">
              <el-select
                v-model="faultForm.responsiblePersons"
                multiple
                placeholder="请选择责任人"
                class="form-select"
                filterable
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="2"
              >
                <el-option
                  v-for="user in userOptions"
                  :key="user.value"
                  :label="user.label"
                  :value="user.value"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="faultForm.remark"
                type="textarea"
                :rows="3"
                placeholder="其他备注信息、处理建议等"
                maxlength="200"
                show-word-limit
                class="form-textarea"
              />
            </el-form-item>
          </div>

          <!-- 状态信息区域 -->
          <div class="form-section">
            <div class="section-title">
              <el-icon><Flag /></el-icon>
              <span>状态信息</span>
            </div>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="故障状态" prop="status">
                  <el-select v-model="faultForm.status" placeholder="请选择故障状态" class="form-select">
                    <el-option label="待处理" value="pending">
                      <el-tag type="info" size="small">待处理</el-tag>
                    </el-option>
                    <el-option label="处理中" value="processing">
                      <el-tag type="warning" size="small">处理中</el-tag>
                    </el-option>
                    <el-option label="已解决" value="resolved">
                      <el-tag type="success" size="small">已解决</el-tag>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="扣除绩效分" prop="deductionScore" class="deduction-score-item">
                  <div class="deduction-score-wrapper">
                    <el-input-number
                      v-model="faultForm.deductionScore"
                      :min="0"
                      :max="100"
                      :precision="1"
                      class="form-number deduction-score-input"
                      placeholder="请输入扣除绩效分"
                      controls-position="right"
                    />
                    <span class="input-suffix">分</span>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <div class="footer-actions">
            <el-button type="primary" @click="submitForm" :loading="submitLoading" size="large">
              <el-icon><Check /></el-icon>
              {{ isEdit ? '更新记录' : '创建记录' }}
            </el-button>
            <el-button @click="dialogVisible = false" size="large">
              <el-icon><Close /></el-icon>
              取消
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>

    <!-- 查看故障详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="故障详情"
      width="700px"
      class="view-dialog"
    >
      <div v-if="currentFault" class="fault-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="项目名称">{{ currentFault.projectName }}</el-descriptions-item>
                     <el-descriptions-item label="故障开始时间">{{ currentFault.faultStartTime }}</el-descriptions-item>
           <el-descriptions-item label="故障解决时间">{{ currentFault.faultEndTime || '未解决' }}</el-descriptions-item>
          <el-descriptions-item label="故障等级">
            <el-tag :type="getSeverityTagType(currentFault.severity)">
              {{ getSeverityText(currentFault.severity) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="故障状态">
            <el-tag :type="getStatusTagType(currentFault.status)">
              {{ getStatusText(currentFault.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="扣除绩效分">
            <el-tag :type="getScoreTagType(currentFault.deductionScore)">
              -{{ currentFault.deductionScore }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="责任人" :span="2">{{ currentFault.responsiblePersons }}</el-descriptions-item>
          <el-descriptions-item label="故障描述" :span="2">{{ currentFault.description }}</el-descriptions-item>
          <el-descriptions-item label="故障原因" :span="2">{{ currentFault.reason }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ currentFault.remark || '无' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentFault.createTime }}</el-descriptions-item>
          
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  Plus,
  Search,
  Clock,
  Check,
  List,
  Grid,
  View,
  Edit,
  Delete,
  Folder,
  InfoFilled,
  Flag,
  Document,
  User,
  Calendar,
  Close
} from '@element-plus/icons-vue'
import { getItemList } from '@/api/project'
import { GetGetOnlineTaskGuarantors } from '@/api/newDemands'
import request from '@/utils/request'

// 响应式数据
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const viewMode = ref<'table' | 'card'>('table')
const currentPage = ref(1)
const pageSize = ref(20)
const faultFormRef = ref<FormInstance>()
const currentFault = ref<any>(null)
const totalCount = ref(0)

// 过滤条件
const filters = reactive({
  project: 0,
  dateRange: [] as string[],
  status: '',
  severity: '',
  keyword: ''
})

// 故障表单
const faultForm = reactive({
  id: 0,
  projectId: 0,
  faultStartTime: '',
  faultEndTime: '',
  description: '',
  reason: '',
  responsiblePersons: [] as string[],
  deductionScore: 0,
  severity: 'medium',
  status: 'pending',
  remark: ''
})

// 表单验证规则
const faultRules: FormRules = {
  projectId: [{ 
    required: true, 
    validator: (_rule: any, value: any, callback: any) => {
      if (value === 0) {
        callback(new Error('请选择项目'))
      } else {
        callback()
      }
    }, 
    trigger: 'change' 
  }],
     faultStartTime: [{ required: true, message: '请选择故障开始时间', trigger: 'change' }],
   faultEndTime: [{ required: false, message: '请选择故障解决时间', trigger: 'change' }],
  description: [{ required: true, message: '请输入故障描述', trigger: 'blur' }],
  reason: [{ required: true, message: '请输入故障原因', trigger: 'blur' }],
  responsiblePersons: [{ required: true, message: '请选择责任人', trigger: 'change' }],
  deductionScore: [{ required: true, message: '请输入扣除绩效分', trigger: 'blur' }],
  severity: [{ required: true, message: '请选择故障等级', trigger: 'change' }],
  status: [{ required: true, message: '请选择故障状态', trigger: 'change' }]
}

// 模拟数据
const faultList = ref([
  {
    id: 1,
    projectId: 0, // 将在获取项目列表后更新
    projectName: '电商平台',
         faultStartTime: '2024-01-15 14:30:00',
     faultEndTime: '2024-01-16 10:00:00',
    description: '用户登录功能异常，无法正常登录系统',
    reason: '数据库连接池配置不当，导致连接超时',
    responsiblePersons: '张三, 李四',
    deductionScore: 5.0,
    severity: 'high',
    status: 'resolved',
    remark: '已优化数据库连接池配置',
    createTime: '2024-01-15 15:00:00',
    updateTime: '2024-01-16 10:00:00'
  },
  {
    id: 2,
    projectId: 0, // 将在获取项目列表后更新
    projectName: '移动端APP',
         faultStartTime: '2024-01-14 09:15:00',
     faultEndTime: '',
    description: 'APP启动时出现白屏，无法正常显示内容',
    reason: '前端资源加载失败，CDN节点异常',
    responsiblePersons: '王五',
    deductionScore: 3.0,
    severity: 'medium',
    status: 'processing',
    remark: '正在联系CDN服务商处理',
    createTime: '2024-01-14 09:30:00',
    updateTime: '2024-01-15 16:00:00'
  },
  {
    id: 3,
    projectId: 0, // 将在获取项目列表后更新
    projectName: '后台管理系统',
         faultStartTime: '2024-01-13 16:45:00',
     faultEndTime: '2024-01-14 11:00:00',
    description: '数据导出功能异常，导出的Excel文件损坏',
    reason: '文件流处理逻辑错误，导致文件写入不完整',
    responsiblePersons: '赵六, 钱七',
    deductionScore: 4.0,
    severity: 'medium',
    status: 'resolved',
    remark: '已修复文件流处理逻辑',
    createTime: '2024-01-13 17:00:00',
    updateTime: '2024-01-14 11:00:00'
  }
])

// 选项数据
const projectOptions = ref<Array<{ value: number; label: string }>>([])
const userOptions = ref<Array<{ value: string; label: string }>>([])

// 计算属性
// 服务端分页：直接展示 faultList，分页由接口返回 totalCount 控制
const paginatedFaults = computed(() => faultList.value)



// 获取项目列表
const fetchProjectList = async () => {
  try {
    const response = await getItemList({})
    if (response && response.data && response.data.code === 200 && response.data.data) {
      // 根据接口返回的数据结构调整
      projectOptions.value = response.data.data.map((item: any) => ({
        value: item.ID,
        label: item.itemName
      }))
      
      // 更新模拟数据中的项目ID，使其与接口数据保持一致
      if (projectOptions.value.length > 0) {
        faultList.value.forEach((fault, index) => {
          const projectIndex = index % projectOptions.value.length
          fault.projectId = projectOptions.value[projectIndex].value
        })
        
        // 设置筛选条件的默认项目为0（全部）
        filters.project = 0
      }
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
    ElMessage.error('获取项目列表失败')
  }
}

// 获取用户列表
const fetchUserList = async () => {
  try {
    const response = await GetGetOnlineTaskGuarantors()
    if (response && response.data && response.data.code === 200 && response.data.data) {
      // 根据接口返回的数据结构调整
      userOptions.value = response.data.data.map((user: any) => ({
        value: user.userName,
        label: user.userName
      }))
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
    // 如果接口失败，使用默认用户数据作为备选
    userOptions.value = [
      { value: '张三', label: '张三' },
      { value: '李四', label: '李四' },
      { value: '王五', label: '王五' },
      { value: '赵六', label: '赵六' },
      { value: '钱七', label: '钱七' },
      { value: '孙八', label: '孙八' }
    ]
  }
}

// 方法
const showAddDialog = () => {
  isEdit.value = false
  dialogVisible.value = true
}

const editFault = (fault: any) => {
  isEdit.value = true
  currentFault.value = fault
  const parseResponsible = (val: any): string[] => {
    if (!val) return []
    if (Array.isArray(val)) return val
    const str = String(val)
    if (str.includes('|')) return str.split('|').map(s => s.trim()).filter(Boolean)
    if (str.includes(',')) return str.split(',').map(s => s.trim()).filter(Boolean)
    if (str.includes('、')) return str.split('、').map(s => s.trim()).filter(Boolean)
    return [str.trim()].filter(Boolean)
  }
  Object.assign(faultForm, {
     id: fault.id,
     projectId: fault.projectId,
     faultStartTime: fault.faultStartTime,
     faultEndTime: fault.faultEndTime,
     description: fault.description,
     reason: fault.reason,
     responsiblePersons: parseResponsible(fault.responsible || fault.responsiblePersons),
     deductionScore: fault.deductionScore,
     severity: fault.severity,
     status: fault.status,
     remark: fault.remark
   })
  dialogVisible.value = true
}

const viewFault = async (fault: any) => {
  try {
    const res = await request({ url: '/item/getFault', method: 'GET', params: { id: fault.id } })
    if (res && res.data && (res.data.code === 200 || res.status === 200)) {
      const it = (res.data.data && (res.data.data.detail || res.data.data)) || {}
      const mapped = {
        id: it.id || it.ID || fault.id,
        projectId: it.itemItemID || it.projectId || fault.projectId || 0,
        projectName: (it.projectName || it.itemName || (() => {
          const p = projectOptions.value.find(op => op.value === (it.itemItemID || it.projectId || fault.projectId))
          return p ? p.label : (fault.projectName || '')
        })()),
        faultStartTime: it.beginTime || it.faultStartTime || fault.faultStartTime || '',
        faultEndTime: it.endTime || it.faultEndTime || fault.faultEndTime || '',
        description: it.faultDesc || it.description || fault.description || '',
        reason: it.faultReason || it.reason || fault.reason || '',
        responsiblePersons: (Array.isArray(it.responsible) ? it.responsible.join(', ') : (it.responsible || fault.responsiblePersons || '')),
        deductionScore: it.deductionScore ?? fault.deductionScore ?? 0,
        severity: (it.faultLevel === '低' ? 'low' : it.faultLevel === '中' ? 'medium' : it.faultLevel === '高' ? 'high' : (it.severity || fault.severity || 'medium')),
        status: (it.faultStatus === '未处理' ? 'pending' : it.faultStatus === '处理中' ? 'processing' : it.faultStatus === '已解决' ? 'resolved' : (it.status || fault.status || 'pending')),
        remark: it.remark || fault.remark || '',
        createTime: it.createAt || it.createTime || fault.createTime || '',
        updateTime: it.updateTime || fault.updateTime || ''
      }
      currentFault.value = mapped
      viewDialogVisible.value = true
    } else {
      ElMessage.error(res?.data?.msg || '获取故障详情失败')
    }
  } catch (error) {
    console.error('获取故障详情失败:', error)
    ElMessage.error('获取故障详情失败')
  }
}

const deleteFault = async (fault: any) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除故障记录吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await request({ url: '/item/deleteFault', method: 'GET', params: { id: fault.id } })
    if (res && res.data && (res.data.code === 200 || res.status === 200)) {
      await fetchFaultList()
      ElMessage.success(res.data.msg || '删除成功')
    } else {
      ElMessage.error(res?.data?.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除故障失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const submitForm = async () => {
  if (!faultFormRef.value) return
  
  try {
    await faultFormRef.value.validate()
    submitLoading.value = true
    
    // 统一状态中文映射与请求报文
    const statusMap: Record<string, string> = {
      pending: '未处理',
      processing: '处理中',
      resolved: '已解决',
      closed: '已关闭'
    }
    const levelMap: Record<string, string> = {
      low: '低',
      medium: '中',
      high: '高',
      critical: '高'
    }
    const payload: any = {
      itemItemID: faultForm.projectId,
      beginTime: faultForm.faultStartTime,
      endTime: faultForm.faultEndTime || '',
      faultStatus: statusMap[faultForm.status] || faultForm.status,
      faultLevel: levelMap[faultForm.severity] || '中',
      deductionScore: faultForm.deductionScore,
      faultDesc: faultForm.description,
      faultReason: faultForm.reason,
      responsible: faultForm.responsiblePersons,
      remark: faultForm.remark
    }
    
    if (isEdit.value) {
      // 更新故障记录：调用后端接口 updateFault
      try {
        const levelMap: Record<string, string> = {
          low: '低',
          medium: '中',
          high: '高',
          critical: '高'
        }
        const updatePayload: any = {
          id: faultForm.id,
          itemItemID: faultForm.projectId,
          beginTime: faultForm.faultStartTime,
          endTime: faultForm.faultEndTime || '',
          faultStatus: statusMap[faultForm.status] || faultForm.status,
          faultLevel: levelMap[faultForm.severity] || '中',
          deductionScore: faultForm.deductionScore,
          faultDesc: faultForm.description,
          faultReason: faultForm.reason,
          responsible: faultForm.responsiblePersons,
          remark: faultForm.remark
        }
        const res = await request({ url: '/item/updateFault', method: 'POST', data: updatePayload })
        if (res && res.data && (res.data.code === 200 || res.status === 200)) {
          await fetchFaultList()
          ElMessage.success(res.data.msg || '更新成功')
        } else {
          ElMessage.error(res?.data?.msg || '更新失败')
          return
        }
      } catch (apiError) {
        console.error('更新故障失败:', apiError)
        ElMessage.error('更新失败')
        return
      }
    } else {
      // 新增故障记录：调用后端接口 createFault
      try {
        const res = await request({ url: '/item/createFault', method: 'POST', data: payload })
        if (res && res.data && (res.data.code === 200 || res.status === 200)) {
          // 创建成功后立即刷新，以获取后端生成的ID与项目信息
          // 创建成功后刷新列表
          await fetchFaultList()
          ElMessage.success(res.data.msg || '创建成功')
        } else {
          ElMessage.error(res?.data?.msg || '创建失败')
          return
        }
      } catch (apiError) {
        console.error('创建故障失败:', apiError)
        ElMessage.error('创建失败')
        return
      }
    }
    
    dialogVisible.value = false
    resetForm()
    currentPage.value = 1
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const resetForm = () => {
  if (faultFormRef.value) {
    faultFormRef.value.resetFields()
  }
  Object.assign(faultForm, {
    id: 0,
    projectId: 0,
    faultStartTime: '',
   faultEndTime: '',
    description: '',
    reason: '',
    responsiblePersons: [] as string[],
    deductionScore: 0,
    severity: 'medium',
    status: 'pending',
    remark: ''
  })
}

// onFiltersChange 替代了旧的 applyFilters
const resetFilters = () => {
  Object.assign(filters, {
    project: 0, // 重置为全部
    dateRange: [] as string[],
    status: '',
    severity: '',
    keyword: ''
  })
  currentPage.value = 1
  fetchFaultList()
}

const onFiltersChange = () => {
  currentPage.value = 1
  fetchFaultList()
}



const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  fetchFaultList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchFaultList()
}

// 工具方法
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    pending: 'warning',
    processing: 'primary',
    resolved: 'success'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    pending: '待处理',
    processing: '处理中',
    resolved: '已解决'
  }
  return textMap[status] || status
}

const getSeverityTagType = (severity: string) => {
  const typeMap: Record<string, string> = {
    low: 'info',
    medium: 'warning',
    high: 'danger',
    critical: 'danger'
  }
  return typeMap[severity] || 'info'
}

const getSeverityText = (severity: string) => {
  const textMap: Record<string, string> = {
    low: '低',
    medium: '中',
    high: '高',
    critical: '紧急'
  }
  return textMap[severity] || severity
}

const getScoreTagType = (score: number) => {
  if (score <= 2) return 'info'
  if (score <= 5) return 'warning'
  if (score <= 10) return 'danger'
  return 'danger'
}

// 计算故障持续时间（小时）
const calculateDuration = (startTime: string, endTime: string) => {
  if (!startTime || !endTime) return '0小时'
  
  const start = new Date(startTime)
  const end = new Date(endTime)
  const diffMs = end.getTime() - start.getTime()
  
  if (diffMs < 0) return '0小时'
  
  const diffHours = Math.round(diffMs / (1000 * 60 * 60) * 10) / 10 // 保留一位小数
  
  if (diffHours < 1) {
    const diffMinutes = Math.round(diffMs / (1000 * 60))
    return `${diffMinutes}分钟`
  } else if (diffHours < 24) {
    return `${diffHours}小时`
  } else {
    const days = Math.floor(diffHours / 24)
    const hours = Math.round((diffHours % 24) * 10) / 10
    return hours > 0 ? `${days}天${hours}小时` : `${days}天`
  }
}

// 生命周期
onMounted(() => {
  currentPage.value = 1
  fetchProjectList() // 获取项目列表
  fetchUserList() // 获取用户列表
  fetchFaultList()
})

// 获取故障列表（服务端分页）
const fetchFaultList = async () => {
  try {
    const statusMap: Record<string, string> = {
      pending: '未处理',
      processing: '处理中',
      resolved: '已解决',
      closed: '已关闭'
    }
    const levelMap: Record<string, string> = {
      low: '低',
      medium: '中',
      high: '高',
      critical: '高'
    }

    const payload: any = {
      itemItemID: filters.project || 0,
      beginTime: (filters.dateRange && filters.dateRange[0]) || '',
      endTime: (filters.dateRange && filters.dateRange[1]) || '',
      faultStatus: filters.status ? (statusMap[filters.status] || filters.status) : '',
      faultLevel: filters.severity ? (levelMap[filters.severity] || '中') : '',
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: filters.keyword || ''
    }

    const res = await request({ url: '/item/getFaultList', method: 'POST', data: payload })
    if (res && res.data && (res.data.code === 200 || res.status === 200)) {
      const list = (res.data.data && (res.data.data.list || res.data.data.rows || res.data.data.items)) || []
      totalCount.value = (res.data.data && (res.data.data.total || res.data.data.count || 0)) || 0

      // 适配后端字段到前端展示结构
      faultList.value = list.map((it: any, idx: number) => ({
        id: it.id || it.ID || idx + 1,
        projectId: it.itemItemID || it.projectId || 0,
        projectName: (it.projectName || it.itemName || (() => {
          const p = projectOptions.value.find(op => op.value === (it.itemItemID || it.projectId))
          return p ? p.label : ''
        })()),
        faultStartTime: it.beginTime || it.faultStartTime || '',
        faultEndTime: it.endTime || it.faultEndTime || '',
        description: it.faultDesc || it.description || '',
        reason: it.faultReason || it.reason || '',
        responsiblePersons: (Array.isArray(it.responsible) ? it.responsible.join(', ') : (it.responsible || it.responsiblePersons || '')),
        deductionScore: it.deductionScore ?? 0,
        severity: (it.faultLevel === '低' ? 'low' : it.faultLevel === '中' ? 'medium' : it.faultLevel === '高' ? 'high' : it.severity || 'medium'),
        status: (it.faultStatus === '未处理' ? 'pending' : it.faultStatus === '处理中' ? 'processing' : it.faultStatus === '已解决' ? 'resolved' : it.faultStatus === '已关闭' ? 'closed' : it.status || 'pending'),
        remark: it.remark || '',
        createTime: it.createAt || it.createTime || it.createdAt || '',
        updateTime: it.updateTime || it.updatedAt || ''
      }))
    } else {
      ElMessage.error(res?.data?.msg || '获取故障列表失败')
    }
  } catch (error) {
    console.error('获取故障列表失败:', error)
    ElMessage.error('获取故障列表失败')
  }
}
</script>

<style scoped lang="scss">
.fault-management-container {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;

  .header-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 32px;
    padding: 24px;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(20px);
    border-radius: 20px;
    box-shadow: 
      0 20px 40px rgba(0, 0, 0, 0.1),
      0 8px 16px rgba(0, 0, 0, 0.05),
      inset 0 1px 0 rgba(255, 255, 255, 0.8);
    border: 1px solid rgba(255, 255, 255, 0.2);
    position: relative;
    overflow: hidden;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: -100%;
      width: 100%;
      height: 100%;
      background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
      transition: left 0.5s;
    }

    &:hover::before {
      left: 100%;
    }

    &:hover {
      transform: translateY(-2px);
      box-shadow: 
        0 25px 50px rgba(0, 0, 0, 0.15),
        0 12px 24px rgba(0, 0, 0, 0.1),
        inset 0 1px 0 rgba(255, 255, 255, 0.9);
    }

    .action-buttons {
      display: flex;
      gap: 16px;

      .el-button {
        border-radius: 12px;
        font-weight: 600;
        padding: 12px 24px;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        position: relative;
        overflow: hidden;

        &::before {
          content: '';
          position: absolute;
          top: 50%;
          left: 50%;
          width: 0;
          height: 0;
          background: rgba(255, 255, 255, 0.3);
          border-radius: 50%;
          transform: translate(-50%, -50%);
          transition: width 0.3s, height 0.3s;
        }

        &:hover::before {
          width: 300px;
          height: 300px;
        }

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 25px rgba(64, 158, 255, 0.4);
        }
      }
    }

    .filter-section {
      .filter-content {
        .filter-row {
          display: flex;
          flex-wrap: wrap;
          gap: 20px;
          align-items: center;

          .filter-item {
            .filter-select,
            .filter-date,
            .filter-input {
              width: 200px;
              border-radius: 12px;
              transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

              &:hover {
                transform: translateY(-1px);
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
              }

              &.el-input__wrapper {
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
                border: 1px solid rgba(0, 0, 0, 0.06);
              }
            }

            .el-button {
              border-radius: 10px;
              font-weight: 600;
              padding: 10px 20px;
              transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

              &:hover {
                transform: translateY(-2px);
                box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
              }
            }
          }
        }
      }
    }
  }

  .fault-list-section {
    .list-card {
      background: rgba(255, 255, 255, 0.95);
      backdrop-filter: blur(20px);
      border-radius: 20px;
      box-shadow: 
        0 20px 40px rgba(0, 0, 0, 0.1),
        0 8px 16px rgba(0, 0, 0, 0.05),
        inset 0 1px 0 rgba(255, 255, 255, 0.8);
      border: 1px solid rgba(255, 255, 255, 0.2);
      overflow: hidden;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

      &:hover {
        transform: translateY(-2px);
        box-shadow: 
          0 25px 50px rgba(0, 0, 0, 0.15),
          0 12px 24px rgba(0, 0, 0, 0.1),
          inset 0 1px 0 rgba(255, 255, 255, 0.9);
      }

      .list-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;
        padding: 24px 24px 20px;
        border-bottom: 2px solid rgba(102, 126, 234, 0.1);
        background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);

        .list-title {
          display: flex;
          align-items: center;
          gap: 16px;
          font-size: 20px;
          font-weight: 700;
          color: #2c3e50;
          text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);

          span {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
          }

          .el-tag {
            border-radius: 20px;
            font-weight: 600;
            padding: 6px 16px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          }
        }

        .list-actions {
          display: flex;
          gap: 16px;

          .el-button-group {
            .el-button {
              border-radius: 12px;
              font-weight: 600;
              padding: 10px 20px;
              transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

              &:hover {
                transform: translateY(-2px);
                box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
              }

              &.is-active {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                border-color: transparent;
                box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
              }
            }
          }
        }
      }

             .table-view {
         padding: 0 24px;
         max-height: 600px;
         overflow: hidden;

         .fault-table {
           margin-bottom: 24px;
           border-radius: 16px;
           overflow: hidden;
           box-shadow: 0 8px 25px rgba(0, 0, 0, 0.08);

           // 表格滚动条样式
           ::-webkit-scrollbar {
             width: 8px;
             height: 8px;
           }

           ::-webkit-scrollbar-track {
             background: rgba(102, 126, 234, 0.1);
             border-radius: 4px;
           }

           ::-webkit-scrollbar-thumb {
             background: rgba(102, 126, 234, 0.3);
             border-radius: 4px;
             
             &:hover {
               background: rgba(102, 126, 234, 0.5);
             }
           }

          .el-table__header {
            th {
              background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%) !important;
              color: #2c3e50;
              font-weight: 700;
              border-bottom: 2px solid rgba(102, 126, 234, 0.1);
            }
          }

          .el-table__row {
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

            &:hover {
              background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
              transform: scale(1.01);
            }
          }

          .el-tag {
            border-radius: 20px;
            font-weight: 600;
            padding: 4px 12px;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
          }
        }
      }

             .card-view {
         padding: 0 24px;
         max-height: 600px;
         overflow-y: auto;
         scrollbar-width: thin;
         scrollbar-color: rgba(102, 126, 234, 0.3) rgba(102, 126, 234, 0.1);

         &::-webkit-scrollbar {
           width: 8px;
         }

         &::-webkit-scrollbar-track {
           background: rgba(102, 126, 234, 0.1);
           border-radius: 4px;
         }

         &::-webkit-scrollbar-thumb {
           background: rgba(102, 126, 234, 0.3);
           border-radius: 4px;
           
           &:hover {
             background: rgba(102, 126, 234, 0.5);
           }
         }

         .fault-cards {
           display: grid;
           grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
           gap: 24px;
           margin-bottom: 24px;

          .fault-card {
            border-radius: 16px;
            border: 1px solid rgba(102, 126, 234, 0.1);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            overflow: hidden;
            position: relative;

            &::before {
              content: '';
              position: absolute;
              top: 0;
              left: 0;
              right: 0;
              height: 4px;
              background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            }

            &:hover {
              transform: translateY(-8px) scale(1.02);
              box-shadow: 
                0 25px 50px rgba(0, 0, 0, 0.15),
                0 12px 24px rgba(0, 0, 0, 0.1);
            }

            .card-header {
              display: flex;
              justify-content: flex-end;
              align-items: center;
              margin-bottom: 20px;
              padding: 20px 20px 0;

              .fault-status {
                font-weight: 600;
                font-size: 14px;
                color: #667eea;
                text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
              }
            }

            .card-content {
              padding: 0 20px;

              .fault-project {
                display: flex;
                align-items: center;
                gap: 10px;
                margin-bottom: 16px;
                color: #5a6c7d;
                font-weight: 600;

                .el-icon {
                  color: #667eea;
                  font-size: 18px;
                }
              }

              .fault-description {
                margin-bottom: 20px;
                color: #2c3e50;
                line-height: 1.6;
                font-weight: 500;
                display: -webkit-box;
                -webkit-line-clamp: 2;
                line-clamp: 2;
                -webkit-box-orient: vertical;
                overflow: hidden;
              }

              .fault-details {
                .detail-item {
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                  margin-bottom: 12px;
                  padding: 8px 0;

                  .label {
                    color: #7f8c8d;
                    font-size: 14px;
                    font-weight: 500;
                  }

                  .value {
                    color: #2c3e50;
                    font-size: 14px;
                    font-weight: 600;
                  }

                  .el-tag {
                    border-radius: 20px;
                    font-weight: 600;
                    padding: 4px 12px;
                    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
                  }
                }
              }
            }

            .card-footer {
              display: flex;
              gap: 12px;
              justify-content: flex-end;
              margin-top: 20px;
              padding: 20px;
              border-top: 1px solid rgba(102, 126, 234, 0.1);
              background: linear-gradient(135deg, rgba(102, 126, 234, 0.02) 0%, rgba(118, 75, 162, 0.02) 100%);

              .el-button {
                border-radius: 10px;
                font-weight: 600;
                padding: 8px 16px;
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

                &:hover {
                  transform: translateY(-2px);
                  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
                }
              }
            }
          }
        }
      }

             .pagination-wrapper {
         display: flex;
         justify-content: flex-end;
         margin: 24px 0;
         padding: 20px 24px;
         background: linear-gradient(135deg, rgba(102, 126, 234, 0.02) 0%, rgba(118, 75, 162, 0.02) 100%);
         border-top: 1px solid rgba(102, 126, 234, 0.1);

        .el-pagination {
          .el-pager li {
            border-radius: 8px;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

            &:hover {
              transform: translateY(-2px);
              box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            }

            &.is-active {
              background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
              box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
            }
          }
        }
      }
    }
  }
}

// 表单样式
.fault-form {
  .form-select,
  .form-date,
  .form-number {
    width: 100%;
    border-radius: 12px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
  }

  .el-form-item__label {
    font-weight: 600;
    color: #2c3e50;
  }
}

// 对话框样式
.view-dialog {
  .fault-detail {
    .el-descriptions {
      margin-top: 20px;
      border-radius: 16px;
      overflow: hidden;
      box-shadow: 0 8px 25px rgba(0, 0, 0, 0.08);

      .el-descriptions__header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 16px 20px;
        margin: 0;

        .el-descriptions__title {
          color: white;
          font-weight: 700;
        }
      }

      .el-descriptions__body {
        .el-descriptions__table {
          .el-descriptions__cell {
            padding: 16px 20px;
            border-color: rgba(102, 126, 234, 0.1);

            &.el-descriptions__label {
              background: rgba(102, 126, 234, 0.05);
              font-weight: 600;
              color: #2c3e50;
            }

            &.el-descriptions__content {
              color: #5a6c7d;
              font-weight: 500;
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .fault-management-container {
    padding: 16px;

    .header-section {
      flex-direction: column;
      gap: 20px;
      align-items: stretch;
      padding: 20px;

      .filter-section {
        .filter-content {
          .filter-row {
            flex-direction: column;
            align-items: stretch;
            gap: 16px;

            .filter-item {
              .filter-select,
              .filter-date,
              .filter-input {
                width: 100%;
              }
            }
          }
        }
      }
    }

    .fault-list-section {
      .list-card {
        .list-header {
          flex-direction: column;
          gap: 20px;
          align-items: stretch;
          padding: 20px;

          .list-actions {
            justify-content: center;
          }
        }

        .table-view,
        .card-view {
          padding: 0 20px;
        }

        .card-view {
          .fault-cards {
            grid-template-columns: 1fr;
            gap: 20px;
          }
        }
      }
    }
  }
}

// 动画效果
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.fault-management-container {
  animation: fadeInUp 0.6s cubic-bezier(0.4, 0, 0.2, 1);
}

.header-section,
.fault-list-section .list-card {
  animation: fadeInUp 0.8s cubic-bezier(0.4, 0, 0.2, 1);
}

// 故障对话框样式
.fault-dialog {
  :deep(.el-dialog) {
    border-radius: 16px;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
    overflow: hidden;
  }

  :deep(.el-dialog__header) {
    display: none; // 隐藏默认标题，使用自定义头部
  }

  :deep(.el-dialog__body) {
    padding: 0;
  }

  :deep(.el-dialog__footer) {
    padding: 0;
    border-top: 1px solid #f0f0f0;
  }
}

.dialog-content {
  .fault-form {
    padding: 24px;

    .form-section {
      margin-bottom: 20px;
      padding: 16px;
      background: #fafbfc;
      border-radius: 8px;
      border: 1px solid #e8eaed;
      transition: all 0.3s ease;

      &:hover {
        border-color: #d1d5db;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
      }

      &:last-child {
        margin-bottom: 0;
      }

      .section-title {
        display: flex;
        align-items: center;
        margin-bottom: 12px;
        padding-bottom: 8px;
        border-bottom: 1px solid #e8eaed;
        gap: 6px;

        .el-icon {
          color: #667eea;
          font-size: 16px;
        }

        span {
          font-size: 14px;
          font-weight: 600;
          color: #2c3e50;
        }
      }

      .el-form-item {
        margin-bottom: 16px;

        &:last-child {
          margin-bottom: 0;
        }

        :deep(.el-form-item__label) {
          font-weight: 500;
          color: #374151;
          font-size: 14px;
        }

        .form-select,
        .form-date,
        .form-number {
          width: 100%;
        }

        .form-textarea {
          :deep(.el-textarea__inner) {
            border-radius: 8px;
            border: 1px solid #d1d5db;
            transition: all 0.3s ease;
            font-size: 14px;
            line-height: 1.5;

            &:focus {
              border-color: #667eea;
              box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            }
          }
        }

        .input-suffix {
          margin-left: 8px;
          color: #6b7280;
          font-size: 14px;
        }

        // 扣除绩效分特殊样式
        &.deduction-score-item {
          :deep(.el-form-item__label) {
            color: #e6a23c;
            font-weight: 600;
            position: relative;
            
            &::after {
              content: "⚠️";
              margin-left: 6px;
              font-size: 12px;
            }
          }

          .deduction-score-wrapper {
            display: flex;
            align-items: center;
            gap: 8px;
            white-space: nowrap;
          }

          .deduction-score-input {
            :deep(.el-input-number) {
              border: 2px solid #e6a23c;
              border-radius: 8px;
              background: linear-gradient(135deg, #fff9f0 0%, #fff5e6 100%);
              box-shadow: 0 0 0 3px rgba(230, 162, 60, 0.1);
              transition: all 0.3s ease;
              overflow: hidden;

              &:focus-within {
                border-color: #d97706;
                box-shadow: 0 0 0 3px rgba(230, 162, 60, 0.2);
                background: linear-gradient(135deg, #fff7ed 0%, #fff1e6 100%);
              }

              &:hover {
                border-color: #d97706;
                box-shadow: 0 0 0 3px rgba(230, 162, 60, 0.15);
              }
            }

            :deep(.el-input__inner) {
              border: none;
              background: transparent;
              color: #b45309;
              font-weight: 600;
              box-shadow: none;
              padding: 0 8px;

              &:focus {
                border: none;
                box-shadow: none;
                background: transparent;
              }

              &:hover {
                border: none;
                box-shadow: none;
                background: transparent;
              }
            }

            :deep(.el-input-number__increase),
            :deep(.el-input-number__decrease) {
              background: #e6a23c;
              color: white;
              border: none;
              width: 24px;
              height: 20px;
              line-height: 20px;

              &:hover {
                background: #d97706;
              }

              &:active {
                background: #b45309;
              }
            }

            :deep(.el-input-number__decrease) {
              border-right: 1px solid rgba(255, 255, 255, 0.2);
            }
          }

          .input-suffix {
            color: #e6a23c;
            font-weight: 600;
            font-size: 15px;
            white-space: nowrap;
            flex-shrink: 0;
          }
        }
      }

      :deep(.el-select) {
        .el-input__inner {
          border-radius: 8px;
          border: 1px solid #d1d5db;
          transition: all 0.3s ease;

          &:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
          }
        }
      }

      :deep(.el-date-editor) {
        border-radius: 8px;
        border: 1px solid #d1d5db;
        transition: all 0.3s ease;

        &:focus-within {
          border-color: #667eea;
          box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
      }

      :deep(.el-input-number) {
        width: 100%;

        .el-input__inner {
          border-radius: 8px;
          border: 1px solid #d1d5db;
          transition: all 0.3s ease;

          &:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
          }
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 20px 32px;
  background: #fafbfc;

  .footer-actions {
    display: flex;
    gap: 12px;
  }

  .el-button {
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s ease;

    &.el-button--large {
      padding: 12px 24px;
      font-size: 14px;
    }

    &:not(.el-button--primary) {
      border: 1px solid #d1d5db;
      color: #6b7280;
      background: white;

      &:hover {
        border-color: #9ca3af;
        color: #374151;
        background: #f9fafb;
      }
    }

    &.el-button--primary {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border: none;

      &:hover {
        background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
      }
    }
  }
}

// 移动端适配
@media (max-width: 768px) {
  .fault-dialog {
    :deep(.el-dialog) {
      width: 95% !important;
      margin: 0 auto;
    }
  }

  .dialog-content {
    .fault-form {
      padding: 20px 16px;

      .form-section {
        padding: 16px 12px;
        margin-bottom: 16px;

        .section-title {
          margin-bottom: 10px;
          padding-bottom: 6px;

          span {
            font-size: 13px;
          }
        }
      }
    }
  }

  .dialog-footer {
    padding: 16px 20px;

    .footer-actions {
      width: 100%;
      justify-content: flex-end;
      flex-direction: row;
      gap: 12px;
    }

    .el-button {
      flex: 1;
      max-width: 120px;
    }
  }
}

// 持续时间样式
.duration-text {
  color: #409eff;
  font-weight: 600;
  font-size: 13px;
  background: rgba(64, 158, 255, 0.1);
  padding: 2px 8px;
  border-radius: 4px;
  border: 1px solid rgba(64, 158, 255, 0.2);
}

.duration-ongoing {
  color: #e6a23c;
  font-weight: 600;
  font-size: 13px;
  background: rgba(230, 162, 60, 0.1);
  padding: 2px 8px;
  border-radius: 4px;
  border: 1px solid rgba(230, 162, 60, 0.2);
}

// 滚动条样式
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: rgba(102, 126, 234, 0.1);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 4px;
  
  &:hover {
    background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
  }
}
</style>
